/*
  shaders source code

*/

#ifndef SHADERS_C
#define SHADERS_C

#define GL_GLEXT_PROTOTYPES

#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glx.h>
#include <GL/glu.h>
#include <GL/glext.h>
#include <GL/glcorearb.h>

void* loadTextFile(char* fname) {
  FILE* fp = fopen(fname, "r");
  if(!fp) {
    printf("Can't open file '%s'\n", fname);
    return NULL;
  };
  fseek(fp, 0, SEEK_END);
  long int sz = ftell(fp);
  printf("File %s size: %d\n", fname, sz);
  fseek(fp, 0, SEEK_SET);
  void* buf = malloc(sz+1);
  fread(buf, 1, sz, fp);
  fclose(fp);
  ((char*)buf)[sz] = '\0';
  return buf;
};

unsigned int CreateShader(char* fname, GLenum type) {
  char* msg;

  switch(type) {
    case GL_VERTEX_SHADER:
      msg = "Vertex";
      break;
    case GL_FRAGMENT_SHADER:
      msg = "Fragment";
      break;
    default:
      printf("Wrong shader type\n");
      return 0;
      break;
  };

  void* buf = loadTextFile(fname);
  unsigned int shader = glCreateShader(type);
  glShaderSource(shader, 1 , (const char**)&buf, NULL);
  glCompileShader(shader);

  int success;
  char inf[500];
  glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
  if(!success) {
    glGetShaderInfoLog(shader, 500, NULL, inf);
    printf("%s shader compilation failed: %s\n", msg, inf);
  };
  free(buf);
  return shader;
};

unsigned int CreateShaderProgram(char* fvertex, char* ffragment) {
  unsigned int vertexShader = CreateShader(fvertex, GL_VERTEX_SHADER);
  unsigned int fragmentShader = CreateShader(ffragment, GL_FRAGMENT_SHADER);
  unsigned int shaderProgram = glCreateProgram();
  glAttachShader(shaderProgram, vertexShader);
  glAttachShader(shaderProgram, fragmentShader);
  glLinkProgram(shaderProgram);

  int success;
  char inf[500];
  glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
  if(!success) {
    glGetProgramInfoLog(shaderProgram, 500, NULL, inf);
    printf("Shader program linking error: %s\n", inf);
  };

  glDeleteShader(vertexShader);
  glDeleteShader(fragmentShader);
  return shaderProgram;
};

#endif
